import { getList, setList } from './const/subApps.js'
import { setMainLifeCycle } from './const/mainLifeCycle'
import { rewriteRouter } from './router/rewriteRouter'
import { getCurrentApp } from './utils/index' 
import { prefetch } from './loader/prefetch'

import { Custom } from './customevent'

// customEvent自定义事件测试
let custom = new Custom()
custom.on('test', (data) => {
    console.log('customEvent test==', data.detail)
})
window.custom = custom;

// 路由拦截
rewriteRouter();

// 注册子应用
export const registerMicroApps = (appList, lifeCycle) => {
    
    // 缓存主应用列表
    setList(appList);
    
    // 缓存生命周期
    setMainLifeCycle(lifeCycle)

    // 主应用生命周期处理测试
    // lifeCycle.beforeLoad[0]();
    // setTimeout(() => {
    //     lifeCycle.mounted[0]();
    // }, 3000)
    
}

// 启动微前端框架
export const start = () => {
    // 验证子应用是否为空，空抛出异常
    const apps = getList();
    if(apps.length == 0) {
        throw Error('子应用为空')
    }

    // 查找符合当前的子应用
    const app = getCurrentApp();
    if(app) {
        const { pathname, hash } = window.location
        const url = pathname + hash;
        window.history.pushState('','', url)
        // 保存当前路由
        let rule = app.activeRule
        window.CURRENT_SUB_APP = rule;
        // console.log('保存当前路由url===',  app, window.CURRENT_SUB_APP)
    }

    // 预加载其他子应用,默认不展示
    prefetch()
}